/*
 * Copyright (C) 2015 Drakeet <drakeet.me@gmail.com>
 *
 * This file is part of Meizhi
 *
 * Meizhi is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Meizhi is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Meizhi.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.lzkj.baotouhousingfund.base;

import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.lzkj.baotouhousingfund.R;
import com.lzkj.baotouhousingfund.widget.recyclerview.DivItemDecoration;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.zhy.autolayout.utils.AutoUtils;

import java.lang.ref.WeakReference;


public abstract class ListActivity<T extends BasePresenter, V> extends BaseActivity<T> implements
        OnRefreshLoadmoreListener {


    public AppBarLayout mAppBar;
    public Toolbar      mToolbar;
    public TextView     mToolbarTitle;
    public TextView     mToolbarRight;
    protected boolean mIsHidden = false;

    protected RecyclerView  mRecyclerView;
    protected RefreshLayout mRefreshLayout;
    protected Adapter<V>    mAdapter;

    private View mNotDataView;
    private View mErrorView;

    public void onToolbarClick() {
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_list;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAppBar = (AppBarLayout) findViewById(R.id.app_bar_layout);
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbarTitle = (TextView) findViewById(R.id.toolbar_title);
        mToolbarRight = (TextView) findViewById(R.id.toolbar_right);
        if (mToolbar == null || mAppBar == null) {
            throw new IllegalStateException(
                    "The subclass of ToolbarActivity must contain a toolbar.");
        }
        mToolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onToolbarClick();
            }
        });
        setSupportActionBar(mToolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayShowTitleEnabled(showTitle());
            actionBar.setDisplayHomeAsUpEnabled(canBack());//设置返回箭头显示
        }
        if (Build.VERSION.SDK_INT >= 21) {
            mAppBar.setElevation(10.6f);
        }


        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        mRefreshLayout = (RefreshLayout) findViewById(R.id.refreshLayout);
        mRefreshLayout.setPrimaryColorsId(R.color.colorTheme, android.R.color.white);
        mRefreshLayout.setEnableRefresh(getRefreshEnabled());
        mRefreshLayout.setOnRefreshLoadmoreListener(this);//设置刷新监听
        mRecyclerView.setLayoutManager(getLayoutManager());
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addItemDecoration(new DivItemDecoration(10, false, false));
//        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration
// .VERTICAL_LIST));

        mAdapter = new Adapter<>(getItemLayoutId(), this);
        mRecyclerView.setAdapter(mAdapter);

        mNotDataView = getLayoutInflater().inflate(R.layout.view_empty, (ViewGroup) mRecyclerView
                .getParent(), false);
        mNotDataView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh(mRefreshLayout);
            }
        });
        mErrorView = getLayoutInflater().inflate(R.layout.view_error, (ViewGroup) mRecyclerView
                .getParent(), false);
        mErrorView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh(mRefreshLayout);
            }
        });

    }


    public void setErrorView() {
        mAdapter.setEmptyView(mErrorView);
    }

    public void setNotDataView() {
        mAdapter.setEmptyView(mNotDataView);
    }


    public boolean canBack() {
        return true;
    }

    public boolean showTitle() {
        return false;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        } else {
            return super.onOptionsItemSelected(item);
        }
    }


    protected void setAppBarAlpha(float alpha) {
        mAppBar.setAlpha(alpha);
    }


    protected void hideOrShowToolbar() {
        mAppBar.animate()
                .translationY(mIsHidden ? 0 : -mAppBar.getHeight())
                .setInterpolator(new DecelerateInterpolator(2))
                .start();
        mIsHidden = !mIsHidden;
    }


    protected boolean getRefreshEnabled() {
        return true;
    }

    protected RecyclerView.LayoutManager getLayoutManager() {
        return new LinearLayoutManager(this);
    }

    protected void onItemClick(RecyclerView recycler, View view, int position, long id, V item) {
    }

    private boolean onItemLongClick(RecyclerView recycler, View view, int position, long itemId,
                                    V item) {
        return false;
    }


    protected void onBindViewEvent(final BaseViewHolder helper, final V item) {
        helper.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onItemClick(mRecyclerView, view, helper.getLayoutPosition(), helper.getItemId(),
                        item);
            }
        });
        helper.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                return onItemLongClick(mRecyclerView, view, helper.getLayoutPosition(), helper
                        .getItemId(), item);
            }
        });
    }

    protected abstract void convert(BaseViewHolder helper, V item);

    protected abstract int getItemLayoutId();

    public void notifyDataSetChanged() {
        if (mRecyclerView != null && mRecyclerView.getAdapter() != null) {
            mRecyclerView.getAdapter().notifyDataSetChanged();
        }
    }

    /**
     * 开始刷新
     */
    public void refresh() {
        mRefreshLayout.autoRefresh();
    }

    /**
     * 完成刷新
     */
    public void finishRefresh() {
        mRefreshLayout.finishRefresh();
    }

    /**
     * 全部完成读取更多   设置之后，将不会再触发加载事件
     */
    public void setLoadmoreFinished(boolean isFinished) {
        mRefreshLayout.setLoadmoreFinished(isFinished);
    }

    /**
     * 完成读取更多
     */
    public void finishLoadmore() {
        mRefreshLayout.finishLoadmore();
    }

    /**
     * 设置刷新是否可用
     *
     * @param enable
     */
    public void setEnableRefresh(boolean enable) {
        mRefreshLayout.setEnableRefresh(enable);
    }

    /**
     * 设置读取更多是否可用
     *
     * @param enable
     */
    public void setEnableLoadMore(boolean enable) {
        mRefreshLayout.setEnableLoadmore(enable);
    }


    @Override
    public void onRefresh(RefreshLayout refreshLayout) {

    }

    @Override
    public void onLoadmore(RefreshLayout refreshLayout) {

    }

    protected static class Adapter<V> extends BaseQuickAdapter<V, ViewHolder> {
        private WeakReference<ListActivity> mReference;

        Adapter(int layoutResId, ListActivity activity) {
            super(layoutResId);
            mReference = new WeakReference<>(activity);
        }

        @Override
        protected void convert(ViewHolder helper, V item) {
            ListActivity activity = mReference.get();
            if (activity != null) {
                activity.convert(helper, item);
            }
            activity.onBindViewEvent(helper, item);
        }

    }

    private static class ViewHolder extends BaseViewHolder {

        public ViewHolder(View view) {
            super(view);
            AutoUtils.autoSize(view);
        }
    }
}
